//
//  JJImagePicker.swift
//  JJImagePicker
//
//  Created by 李加建 on 2021/5/31.
//

import Photos
import UIKit

public class ImagePickerManager {
    public enum SourceType: Int {
        case camera = 0
        case photoLibrary = 1
    }

    /// 默认 photoLibrary
    public var sourceType: SourceType = .photoLibrary

    /// 是否可以编辑 true
    public var allowsEditing: Bool = true

    /// 每行数量  4
    public var lineCount: Int = 4

    /// 间距 2
    public var lineSpacing: CGFloat = 2.0

    /// 编辑的图片
    public var editImage: UIImage?

    public weak var delegate: ImagePickerManagerDelegate?
    
    public init() {}

    public func present(in viewController: UIViewController?) {
        if sourceType == .photoLibrary {
            let next = ImagePickerController(manager: self)
            let navi = ImagePickerNavigationController(rootViewController: next)
            navi.modalPresentationStyle = .fullScreen
            viewController?.present(navi, animated: true, completion: nil)
        } else if sourceType == .camera {
            let next = CameraViewController(manager: self)
            let navi = ImagePickerNavigationController(rootViewController: next)
            navi.modalPresentationStyle = .fullScreen
            viewController?.present(navi, animated: true, completion: nil)
        }
    }
}

public extension ImagePickerManager {
    /// 相册授权
    static func photoLibrary(requestAccess complete: @escaping (Bool) -> Void) {
        if #available(iOS 14, *) {
            PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
                DispatchQueue.main.async {
                    switch status {
                    case .limited:
                        complete(true)
                    case .authorized:
                        complete(true)
                    default:
                        complete(false)
                    }
                }
            }
        } else {
            PHPhotoLibrary.requestAuthorization { status in
                DispatchQueue.main.async {
                    switch status {
                    case .authorized:
                        complete(true)
                    default:
                        complete(false)
                    }
                }
            }
        }
    }

    /// 相机授权
    static func captureDevice(requestAccess complete: @escaping (Bool) -> Void) {
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                complete(granted)
            }
        }
    }
}

public protocol ImagePickerManagerDelegate: AnyObject {
    func didSeletedImage(_ image: UIImage)
}

extension ImagePickerManagerDelegate {
    func didSeletedImage(_: UIImage) {}
}
